<?php  
//Set values for page
$page_title = "Checkout";
$current_page = "Checkout";
require_once 'global.inc.php';  
$pass = DB_PASSWORD;
$error = "";

function get_price($pid, $pass){
	$connection = mysql_connect('localhost', 'root', $pass);
	mysql_select_db('ecom');
	$result=mysql_query("select price from items where item_id=$pid") or die("select price from items where item_id=$pid"."<br/><br/>".mysql_error());
	$row = mysql_fetch_array($result);
	return $row['price'];
}

if(isset($_REQUEST['checkout_place_order'])){
	//check to see if they're logged in
	if(isset($_SESSION['logged_in'])) {
		$user = unserialize($_SESSION['user']);
	
		$connection = mysql_connect('localhost', 'root', $pass);
		mysql_select_db('ecom');
		$date = date("Y-m-d H:i:s",time());
		$payment_method = $_REQUEST['payment_method'];
		$customerid = $user->id;
	
		//INSERT INTO `ecom`.`cart` (`uid`, `cus_id`, `checkout_id`, `date`) VALUES (NULL, '1', '1', '2013-08-20 21:11:20');
		$result = mysql_query("INSERT INTO `ecom`.`cart` (`uid`, `cus_id`, `checkout_id`, `payment_method`, `date`) VALUES (NULL, '$customerid', '','$payment_method', '$date')");
		$orderid = mysql_insert_id();
	
		foreach($_SESSION['cart'] as $product_id => $quantity) {
			$price = get_price($product_id, $pass);
			//INSERT INTO `ecom`.`cart_detail` (`uid`, `cart_id`, `product_id`, `amount`, `price`) VALUES ('', '1', '1', '2', '123');
			mysql_query("INSERT INTO `ecom`.`cart_detail` (`uid`, `cart_id`, `product_id`, `amount`, `price`) VALUES ('', '$orderid', '$product_id', '$quantity', '$price')");
		}
		mysql_close($connection);
		unset($_SESSION['cart']);
		header("Location: thankyou.php"); 
		//die('Thank You! your order has been placed!');

	} else {
		$username = $_REQUEST['username'];
		$email = $_REQUEST['email'];
		$password = $_REQUEST['password'];
		$confirmPassword = $_REQUEST['confirm_password'];
		$address = $_REQUEST['address'];
		$phone = $_REQUEST['phone'];
		$firstname = $_REQUEST['firstname'];
		$lastname = $_REQUEST['lastname'];
		$company = $_REQUEST['company'];
		$city = $_REQUEST['city'];
		$country = $_REQUEST['country'];
		$postcode = $_REQUEST['postcode'];
		if (isset($_REQUEST['createaccount'])) {
			$createaccount= $_REQUEST['createaccount'];
			//die($createaccount);
			
		} else {
			$createaccount = 0;
			//die('test');
		}
		$payment_method = $_REQUEST['payment_method'];
		//$date = date('Y-m-d');
		$date = date("Y-m-d H:i:s",time());
		
		//initialize variables for form validation
		$success = true;
		$userTools = new UserTools();
	
		//validate that the form was filled out correctly
		//check to see if user name already exists
		if($userTools->checkUserExists($username, $email)) {
			$error .= "That username or email is already taken.<br/> \n\r";
			$success = false;
		}
	
		//check to see if passwords match
		if ($createaccount) {
			if(($password=='')||($password != $confirmPassword)) {
				$error .= "Passwords do not match.<br/> \n\r";
				$success = false;
			}
		}

		if($success) {
	
			$connection = mysql_connect('localhost', 'root', $pass);
			mysql_select_db('ecom');
			//INSERT INTO `ecom`.`users` (`id`, `username`, `password`, `email`, `join_date`, `firstname`, `lastname`, `company`, `address`, `city`, `country`, `postcode`, `phone`, `have_account`) 
			//VALUES (NULL, 'dara', MD5('123'), 'dara@test.com', '2013-08-20 21:00:09', 'Dara', 'May', 'WE', '#123', 'PP', 'Cambodia', '888', '092123123', '1');
			$sql = '';
			if ($createaccount) {
				$sql .= "INSERT INTO `ecom`.`users` (`id`, `username`, `password`, `email`, `join_date`, `firstname`, `lastname`, `company`, `address`, `city`, `country`, `postcode`, `phone`, `have_account`) ";
				$sql .= "VALUES (NULL, '$username', MD5('$password'), '$email', '".$date."', '$firstname', '$lastname', '$company', '$address', '$city', '$country', '$postcode', '$phone', '$createaccount');";
				//die($sql);
			} else {
				$sql .= "INSERT INTO `ecom`.`users` (`id`, `email`, `join_date`, `firstname`, `lastname`, `company`, `address`, `city`, `country`, `postcode`, `phone`, `have_account`) ";
				$sql .= "VALUES (NULL,'$email', '".$date."', '$firstname', '$lastname', '$company', '$address', '$city', '$country', '$postcode', '$phone', '$createaccount');";
				//die($sql);
			}

			$result = mysql_query($sql);

			$customerid = mysql_insert_id();

			//INSERT INTO `ecom`.`cart` (`uid`, `cus_id`, `checkout_id`, `date`) VALUES (NULL, '1', '1', '2013-08-20 21:11:20');
			$result = mysql_query("INSERT INTO `ecom`.`cart` (`uid`, `cus_id`, `checkout_id`, `payment_method`, `date`) VALUES (NULL, '$customerid', '','$payment_method', '$date')");
			$orderid = mysql_insert_id();

			foreach($_SESSION['cart'] as $product_id => $quantity) {
				$price = get_price($product_id, $pass);
				//INSERT INTO `ecom`.`cart_detail` (`uid`, `cart_id`, `product_id`, `amount`, `price`) VALUES ('', '1', '1', '2', '123');
				mysql_query("INSERT INTO `ecom`.`cart_detail` (`uid`, `cart_id`, `product_id`, `amount`, `price`) VALUES ('', '$orderid', '$product_id', '$quantity', '$price')");
			}
			mysql_close($connection);
			unset($_SESSION['cart']);
			header("Location: thankyou.php"); 
			//die('Thank You! your order has been placed!');
		}
	}
}


?>
<!DOCTYPE html>
<html lang="en">
	<?php include 'includes/header.php';?>
<body>
	<?php include 'includes/menu.php';?>
	<?php //include 'includes/slideshow.php';?>
	<div class="container" style="margin-top:60px;">
		<?php include 'includes/widget-login.php';?>
		<div class="row">
			<div class="span12">  
			</div>
		</div>
		<div class="row">
			<div class="span12">
				<?php echo ($error != "") ? $error : ""; ?>
				<form action="billing.php" class="checkout" method="post" name="checkout">
					<div id="customer_details" class="col2-set">
					<?php if(!(isset($_SESSION['logged_in']))) { ?>
					<div class="col-1">
						<h3>Billing Address</h3>
						<label class="" for="billing_first_name">First Name </label><input type="text" value="" placeholder="" id="billing_first_name" name="firstname" class="input-text">
						<label class="" for="billing_last_name">Last Name </label><input type="text" value="" placeholder="" id="billing_last_name" name="lastname" class="input-text">
						<label class="" for="billing_company">Company Name</label><input type="text" value="" placeholder="" id="billing_company" name="company" class="input-text">
						<label class="" for="billing_address_1">Address </label><input type="text" autocomplete="no" value="" placeholder="Street address" id="billing_address_1" name="address" class="input-text">
						<label class="" for="billing_city">Town / City </label><input type="text" autocomplete="no" value="" placeholder="City" id="billing_city" name="city" class="input-text">
						<label class="" for="billing_state">County </label><input type="text" autocomplete="no" id="billing_state" name="country" placeholder="County" value="" class="input-text">
						<label class="" for="billing_postcode">Postcode</label><input type="text" autocomplete="no" value="" placeholder="Postcode" id="billing_postcode" name="postcode" class="input-text">
						<label class="" for="billing_email">Email Address </label><input type="text" value="" placeholder="" id="billing_email" name="email" class="input-text">
						<label class="" for="billing_phone">Phone </label><input type="text" value="" placeholder="" id="billing_phone" name="phone" class="input-text">
						<label class="checkbox" for="createaccount"><input type="checkbox" value="0" name="createaccount" id="createaccount" class="input-checkbox"> Create an account?</label>
						
						
						<div class="create-account" style="display: none;">
							<p>Create an account by entering the information below. If you are a returning customer please login at the top of the page.</p>
							<label class="" for="account_username">Account username</label><input type="text" value="" placeholder="Username" id="account_username" name="username" class="input-text">
							<label class="" for="account_password">Account password</label><input type="password" value="" placeholder="Password" id="account_password" name="password" class="input-text">
							<label class="hidden" for="account_password-2">Confirm password</label><input type="password" value="" placeholder="Confirm password" id="account_password-2" name="confirm_password" class="input-text">
						</div>
					</div>
					<?php };?>
					</div>
					<h3 id="order_review_heading">Your order</h3>
					<div id="order_review">
						<table class="table">
							<thead>
								<tr>
									<th class="product-name">Product</th>
									<th class="product-total">Total</th>
								</tr>
							</thead>
							
							<tbody>
								<?php 
								$connection = mysql_connect('localhost', 'root', $pass);
								mysql_select_db('ecom');
								$total = '';
								
								foreach($_SESSION['cart'] as $product_id => $quantity) {
									$sql = sprintf("SELECT item_name, description, price FROM items WHERE item_id = %d;", $product_id);
									$result = mysql_query($sql);
									if(mysql_num_rows(mysql_query($sql)) > 0) {
										list($name, $description, $price) = mysql_fetch_row($result);
										$line_cost = $price * $quantity; //work out the line cost
										$total = $total + $line_cost; //add to the total cost
								?>
								<tr class="checkout_table_item">
									<td class="product-name"><?php echo $name;?><strong class="product-quantity"> X <?php echo $quantity;?></strong></td>
									<td class="product-total"><span class="amount">$<?php echo $line_cost;?></span></td>
								</tr>
								<?php
									}
								}
								mysql_close($connection);
								?>
							</tbody>
							<tfoot>
								<tr class="cart-subtotal">
									<th>Cart Subtotal</th>
									<td><span class="amount">$<?php echo $total;?></span></td>
								</tr>
								<tr class="total">
									<th><strong>Order Total</strong></th>
									<td>
										<strong><span class="amount">$<?php echo $total;?></span></strong>
									</td>
								</tr>
							</tfoot>
						</table>
						<div id="payment">
							<label class="radio">
								<input type="radio" name="payment_method" id="payment_method" value="cod" checked>
								Cash on Delivery
							</label>
							<label class="radio">
								<input type="radio" name="payment_method" id="payment_method" value="wing">
								Pay by Wing Account
							</label>
							<div class="form-row place-order">
								<input type="submit" value="Place order" id="place_order" name="checkout_place_order" class="btn">
							</div>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
	<?php include 'includes/footer.php';?>
	<!-- javascript -->
	<script src="js/jquery.js"></script>
	<script src="js/bootstrap.js"></script>
	<script language="javascript">
		$('#createaccount').change(function(){
			if ($(this).is(':checked')) {
				$(this).val(1);
			} else {
				$(this).val(0);
			}
			$('.create-account').toggle();
		});
	</script>
	</body>
</html>